<template>
    <div>
        <!-- 旧版的选择 -->
        <component v-if="componentType === 1 || componentType === 3" :is="component.component" v-model="computedValue"
            v-bind=componentProps @update="handleChange" @input="handleChange">
        </component>
        <!-- 新版调接口的下拉选择 -->
        <div v-else-if="componentType === 2">
            <biz-form-remote-select 
                cleared 
                :field="field" 
                :placeholder="component.bind.placeholder"
                :remoteMethod="getFixed" 
                :valueKey="valueKey" 
                :value="bizSelectValue" 
                :multiple="!!(field.setting || {isMultiple: false}).isMultiple"
                v-bind="$attrs"
                @input="handleChange">
                <div class="form-remote-select-option" slot="option" slot-scope="{ option }">
                    <div v-if="field.fieldType === 'related_task'">
                        <div>{{ option.taskNo }}</div>
                    </div>
                    <div v-else-if="field.fieldType === 'customer'">
                        <h3>{{ option.name }}</h3>
                        <div>
                            <div class="customer-template-option-content-text">
                                <label>{{$t('common.base.phone')}}：</label>
                                <span>{{ option.lmPhone || '' }}</span>
                            </div>
                            <div class="customer-template-option-content-text">
                                <label>{{$t('common.base.serialNumber')}}：</label>
                                <span>{{ option.serialNumber }}</span>
                            </div>
                        </div>
                    </div>
                    <div v-else-if="field.fieldType === 'product'">
                        <h3>{{ option.name }}</h3>
                        <div class="service-template-option-content">
                            <span class="service-template-option-content-text">
                                <label>{{ $t('common.fields.serialNumber.displayName') }}：</label>
                                <span>{{ option.serialNumber }}</span>
                            </span>
                            <span class="service-template-option-content-text">
                                <label>{{ $t('common.fields.type.displayName') }}:</label>
                                <span>{{ option.type }}</span>
                            </span>
                            <span class="service-template-option-content-text">
                                <label>{{ $t('common.fields.customer.displayName') }}：</label>
                                <span>{{ option.customerName || '' }}</span>
                            </span>
                        </div>
                    </div>
                    <div v-else-if="field.fieldType === 'catalogType'">
                        <h3>{{ option.catalogName || '' }}</h3>
                    </div>
                    <div v-else>
                        <div>{{ option.name || '' }}</div>
                    </div>
                </div>
            </biz-form-remote-select>
        </div>
    </div>
</template>

<script>
import { genComponent } from '@src/component/AdvancedSearch/advancedSearch'
import FieldComponents from '@src/component/AdvancedSearch/FieldComponents'
import { getFixedValueList } from '@src/modules/trigger/api/trigger'

export default {
    name: 'fixedInput',
    props: {
        value: {
            type: Array,
            default: ''
        },
        // 选择的字段数据
        field: {
            type: Object,
            default: () => ({})
        },
        // 选择的判断符
        operator: {
            type: String,
            default: ''
        }
    },
    components: {
        ...FieldComponents,
    },
    data() {
        return {
            // 这些类型从新接口获取数据，有一个特殊的是目前只有客户模块下的服务部门，当enName==tags，fieldType传tag
            fieldTypeList: ['related_task', 'customer', 'product', 'linkman', 'user', 'tag', 'role', 'catalogType'],
        }
    },
    computed: {
        bizSelectValue() {
            let valueArr = JSON.parse(this.value[0] || '[]')
            if (this.field.fieldType === 'catalogType') {
                valueArr = valueArr.map(value => {
                    return {
                        name: value.catalogName,
                        ...value
                    }
                })
                return valueArr
            }
            return valueArr
        },
        component() {
            return genComponent({
                field: {
                    formType: this.field.fieldType,
                    fieldName: this.field.enName,
                },
                operator: this.operator,
                isInsert: false,
                isConnector: false
            })
        },
        componentProps() {
            return {
                ...this.component.bind,
                value: this.value,
                field: {
                    ...this.field,
                    formType: this.field.fieldType || '',
                    fieldName: this.field.enName || '',
                    displayName: this.field.cnName || '',
                },
                type: ['planStartTime', 'planEndTime'].includes(this.field.fieldType) ? 'datetime'  : this.field.fieldType,
                isConnector: false,
                multiple: this.field.fieldType === 'user' ? (this.field.setting?.isMultiple || false) : false
            };
        },
        componentType() {
            if (this.component.component === 'date-search' && this.component?.bind?.isRange) {
                // 日期类型的返回值是一个数组,其他类型取数组第一项即可
                return 1;
            } else if (this.fieldTypeList.some(i => i === this.field.fieldType) || this.field.enName === 'tags'){
                // 新接口返回的固定值
                return 2;
            }
            return 3
        },
        computedValue() {
            if (this.componentType === 1 || this.component.component === 'text-search') {
                // 如果当前是日期类型，或当前组件是一个单行文本的时返回源数据
                return this.value;
            } else {
                try {
                    const parsed = JSON.parse(this.value[0]);
                    if (typeof parsed === 'object' && parsed !== null) {
                        return parsed;
                    } else {
                    // 如果解析结果不是对象或数组，则返回原始字符串
                        return this.value[0];
                    }
                } catch (e) {
                    return this.value[0];
                }
            }
        },
        valueKey() {
            if (this.field.fieldType === 'catalogType') {
                return 'catalogId'
            }
            if (this.field.fieldType === 'related_task') {
                return 'taskNo';
            } 
            
            return 'id';
        },
    },
    methods: {
        handleChange(val) {
            if (this.componentType === 1) {
                this.$emit('input', val);
            } else if (this.componentType === 2) {
                this.$emit('input', [JSON.stringify(val)]);
            } else {
                if (typeof val === 'object') {
                    // TODO 这里改动需要改动老组件，整个数据结构需要一个中间层来转换

                    if (this.field.fieldType === 'cascader' && this.field.setting?.isMulti) {
                        this.$emit('input', [JSON.stringify(val)], {
                            _isMultiCascader: true
                        });
                        return
                    }
                    this.$emit('input', [JSON.stringify(val)]);
                } else {
                    this.$emit('input', [val]);
                }
            }
        },
        async getFixed(params) {
            const res = await getFixedValueList({
                ...params,
                fieldType: this.field.enName === 'tags' ? 'tag' : this.field.fieldType,
            });
            return res.data;
        }
    }
}
</script>

<style scoped lang="scss">
::v-deep .el-select {
    width: 100% !important;
}
::v-deep .content {
    background: #fff;
    height: 100%;
}
::v-deep .base-select-container {
    width: 100%;
}
::v-deep .el-cascader {
    width: 100% !important;
}
.service-template-option-content-text {
    display: flex;
    align-items: center;
}
::v-deep .base-file-del {
    position: absolute;
    right: -10px;
}
</style>
